<template>
  <div id="deptManageDiv">
    <Breadcrumb content="组件模块对照" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findModuleList"></vxe-button>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addBusinessModule()"></vxe-button>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :loading="saveLoading" @click="saveDept"></vxe-button>
        </template>
      </vxe-toolbar>

      <div class="tableBox" ref="eewerrw">
        <vxe-table ref="moduleTable" border="inner" height="auto" class="mytable-scrollbar" :loading="showLoading" :data="departList" :expand-config="{ expandAll: true, reserve: true }" @current-change="deptRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
            isArrow: true,
            isTab: true,
            isEdit: true
          }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
          <vxe-column field="moduleType" title="组件类型" tree-node :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input type="text" :underline="false" v-model="row.moduleType"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="moduleName" title="组件名称" tree-node :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input type="text" :underline="false" v-model="row.moduleName"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="tableName" title="表名" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
            <template #edit="{ row }">
              <vxe-select v-model="row.tableName" placeholder="请选择数据库表" clearable :filterable="true" transfer @change="tableNameChange(row.tableName)">
                <vxe-option v-for="resultSign in databaseTableList" :key="resultSign.TABLE_NAME" :label="resultSign.TABLE_NAME" :value="resultSign.TABLE_NAME"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="outField" title="输出字段" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" width="200px" align="left">
            <template #edit="{ row }">
              <vxe-select v-model="row.outField" placeholder="" clearable transfer class-name="width-100-percentage">
                <vxe-option v-for="(item, index) in fieldListByTable" :key="index" :label="item.columnName" :value="item.columnName"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="showField" title="字段名称" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" width="200px" align="left">
            <template #edit="{ row }">
              <vxe-select v-model="row.showField" placeholder="" clearable transfer class-name="width-100-percentage">
                <vxe-option v-for="(item, index) in fieldListByTable" :key="index" :label="item.columnName" :value="item.columnName"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="showFieldes" title="展示更多字段" tree-node :edit-render="{}">
            <template #edit="{ row }">
              <vxe-select v-model="row.showFieldes" placeholder="" clearable multiple transfer class-name="width-100-percentage">
                <vxe-option v-for="(item, index) in fieldListByTable" :key="index" :label="item.columnName" :value="item.columnName"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="90" align="center" fixed="right">
            <template #default="{ row }">
              <div>
                <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteModule(row)"></vxe-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { funBdsJsResult } from '@/utils/Expression';
import { IsEmpty } from '@/utils/common'; //函数公式

// 全局变量定义区 ==========

let showLoading = ref(false); //刷新加载状态
let saveLoading = ref(false); //保存加载状态
let showDataLoading = ref(false);
let databaseTableList: any = reactive([]);
let fieldListByTable: any = reactive([]);

let searchForm = reactive({
  searchValue: ''
});

let moduleTable = ref(null); //部门表格ref
let departList: any = reactive([]); //部门列表数据
let defaultProps = {
  children: 'children',
  label: 'name'
};
// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  findModuleList();
  getDatabaseGetTableist();
});

// 光标定位在指定字典分类上
function setCurOrgTreeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'orgTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}

// 点击部门当前行触发的事件
function deptRowClick({ row }: any) {
  (proxy.$refs.moduleTable as any).setCurrentRow(row);
  //获取对应表的字段
  getFieldByTable(row.tableName);
}

// 获取部门列表
function findModuleList() {
  showLoading.value = true;
  departList.length = 0;
  const $table = moduleTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
  }

  const url = '/api/qi/qiIndexBusinessModule/findBusinessModules';
  proxy.$http
    .get(url)
    .then((res: any) => {
      departList.push(...res.data);
      if (departList.length > 0) {
        for (const item of departList) {
          item.showFieldes = [];
          if (!IsEmpty(item.showFields)) {
            item.showFieldes = item.showFields.split(',');
          }
        }
      }
      rowClick({ row: departList[0], rowIndex: 0 });

      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
    });
}
// 点击表格当前行
function rowClick({ row, rowIndex }) {
  proxy.$refs.moduleTable.setCurrentRow(row);
  getFieldByTable(row.tableName);
}
// 获取表列表
function getDatabaseGetTableist() {
  databaseTableList.length = 0;
  const url = '/api/sys/basDictTable/findAllTableList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.status.code === 1) {
        databaseTableList.push(...res.data);
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
//装饰器中的参数是方法名，用来传递给父组件
function tableNameChange(tableName) {
  //获取对应表的字段
  getFieldByTable(tableName);
}
function getFieldByTable(tableName) {
  fieldListByTable.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTable/getTableColumns';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: tableName } })
    .then((res: any) => {
      fieldListByTable.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取设计模式选择字典失败',VxeNotifyType.error)
    });
}

// 新建一级/子部门
async function addBusinessModule() {
  // clearForm();
  const $table = moduleTable.value;
  if ($table) {
    // 假设你已经有了表格的引用，比如通过 ref 属性
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      moduleType: '',
      tableName: '',
      outField: '',
      showField: '',
      showFields: '',
      id: ''
    };
    //departList.push(record);
    $table.loadData(departList);
    const { row: newRow } = await $table.insertAt(record);
    // 设置编辑行
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }
  }
}

// 保存
async function saveDept() {
  saveLoading.value = true;
  const $table = moduleTable.value;
  let updateRecords = [];
  let InsertRecords = [];
  let allRecords = [];
  if ($table) {
    updateRecords = await $table.getUpdateRecords().filter((p: any) => {
      if (IsEmpty(p.outField)){
        return ;
      }
      if (!IsEmpty(p.showFieldes)){
        const codes = p.showFieldes.join(',');
        p.showFields = codes;
      }

      return p.id !== '';
    });

    InsertRecords = await $table.getInsertRecords().filter((m: any) => {
      if (IsEmpty(m.outField)){
        return ;
      }
      if (!IsEmpty(m.showFieldes)){
        const codes = m.showFieldes.join(',');
        m.showFields = codes;
      }

      return m.id === '';
    });
    allRecords = [...InsertRecords, ...updateRecords];

    const url = '/api/qi/qiIndexBusinessModule/addOrUpdateBusinessModules';
    proxy.$http
      .post(url, allRecords)
      .then((res: any) => {
        if (res.status.code === 200) {
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage('保存失败', VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
      });
    setTimeout(() => {
      findModuleList();
      saveLoading.value = false;
    }, 500);
  }
}

// 删除部门
function deleteModule(row: any) {
  const $table = moduleTable.value;
  $table.setAllTreeExpand(true);
  proxy
    .$confirm('确定删除此对照？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/qi/qiIndexBusinessModule/deleteBusinessModules';
      if (row.id) {
        proxy.$http.get(url, { params: { id: row.id } }).then((res: any) => {
          if (res.status.code != 200) {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          } else {
            VxeMessage('删除对照成功', VxeNotifyType.success);
          }
          findModuleList();
        });
      } else {
        if ($table) {
          await $table.remove(row);
          VxeMessage('删除对照成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function autoInputCode(row: any) {
  row.inputCode = funBdsJsResult('firstPinYinFun', row.name);
}
</script>

<style lang="scss" scoped>
#deptManageDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }

    // 机构表格
    :deep(.vxe-table--render-default) {
      height: 100%;
    }
    :deep(.vxe-table--render-wrapper) {
      height: 100%;
      background-color: $base-white;
    }
    .tableBox {
      height: calc(100% - 39px);
    }
  }
}
</style>
